<?php

/**
 * Author: LCY<409028735@qq.com>
 * Time: 2021/11/19 14:42
 * Note:
 */

namespace app\admin\model;

use util\Tree;
use think\Model;

class AuthRule extends Model
{

    public function setNameAttr($val)
    {
        if (empty($val)) {
            return '';
        }

        return parse_camel_to_lower($val);
    }
    /**
     * 查询启用的所有规则
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: LCY<409028735@qq.com>
     * Time: 2021/11/21 14:49
     * Note:
     */
    public static function getAvaliableRules()
    {
        $data = self::where('status', 1)->order(['sort' => 'asc'])->select();
        if (!$data) {
            return [];
        }

        return Tree::dataToList($data->toArray());
    }

    /**
     * 获取常见的操作的创建信息（创建列表菜单的时候生成-添加、修改、删除、排序等）
     *
     * @param integer $pid 父级菜单id
     * @param string $pname 父级的权限标识
     * @param array $operates 需要生成的常见操作的
     * @return array
     */
    public static function getChildrenInfos($pid = 0, $pname = '', $operates = [])
    {
        if (empty($pid) || empty($pname) || empty($operates)) {
            return [];
        }
        list($controller) = explode('/', $pname);
        $menus = [];
        foreach ($operates as $operate) {
            $menus[] = [
                'is_menu' => 0,
                'pid' => $pid,
                'title' => self::getOperateTitle($operate),
                'name' => $controller . '/' . $operate
            ];
        }
        return $menus;
    }

    /**
     * 获取常见操作的中文标题
     *
     * @param string $operate
     * @return string
     */
    public static function getOperateTitle($operate)
    {
        $title = '未知操作';
        switch ($operate) {
            case 'index':
                $title = '查看';
                break;
            case 'add':
                $title = '添加';
                break;
            case 'edit':
                $title = '修改';
                break;
            case 'del':
                $title = '删除';
                break;
            case 'sort':
                $title = '排序';
                break;
            case 'toggle':
                $title = '状态切换';
                break;
            case 'detail':
                $title = '查看详情';
                break;
            case 'multi':
                $title = '批量操作';
                break;
        }

        return $title;
    }
}
